# -*- coding: utf-8 -*-
# @Time: 2025/6/29 21:52
# @Author: wzd
# @Email: 2146333089@qq.com
# @File: file2md.py
from pathlib import Path
from pdf2md import pdf_to_markdown
import mammoth


def convert_to_markdown(input_path, output_dir):
    """将任意文档转换为Markdown格式"""
    output_path = output_dir / (input_path.stem + ".md")

    if input_path.suffix == ".pdf":
        # PDF转Markdown（含表格处理）
        md_text = pdf_to_markdown.convert(input_path, include_tables=True)
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(md_text)

    elif input_path.suffix == ".docx":
        # Word转Markdown
        with open(input_path, "rb") as docx_file:
            result = mammoth.convert_to_markdown(docx_file)
            with open(output_path, "w", encoding="utf-8") as f:
                f.write(result.value)

    elif input_path.suffix == ".pptx":
        # PPT转Markdown（提取文本+备注）
        from pptx import Presentation
        prs = Presentation(input_path)
        text_content = []
        for slide in prs.slides:
            for shape in slide.shapes:
                if hasattr(shape, "text"):
                    text_content.append(shape.text)
            if slide.has_notes_slide:
                text_content.append(slide.notes_slide.notes_text_frame.text)
        with open(output_path, "w", encoding="utf-8") as f:
            f.write("\n\n".join(text_content))

    return output_path


# 批量转换整个目录
input_dir = Path("./原始书籍")
output_dir = Path("./标准化书籍")
output_dir.mkdir(exist_ok=True)

for file in input_dir.glob("*.*"):
    if file.suffix.lower() in [".pdf", ".docx", ".pptx", ".epub"]:
        convert_to_markdown(file, output_dir)